import React, {useEffect, useRef} from 'react';
import {App, Button, Flex, Spin} from "antd";
import Tree from "antd/es/tree/Tree";
import {Divider} from "antd/lib";
import type {DataNode} from "antd/es/tree";
import {compareArray} from "../../util/compare";
import {requestGet, requestPost} from "../../util/request";
import LogFactory from "../../log/LogFactory";
import {AuthorityHandleTreeData} from "../../type/AuthorityHandleTreeData";
import {parseIcon} from "../../util/Icon";

const log = LogFactory.getLog("TreeEnhance");

interface TreeEnhanceProps {
    /**
     * 更新树时候的主要id
     */
    id: number,
    /**
     * 渲染数据请的求地址
     */
    dataUrl: string,
    /**
     * 更新数据的请求地址
     */
    updateUrl: string,

    refreshUrl?: string,
}

const TreeEnhance = ({id,dataUrl,updateUrl,refreshUrl}: TreeEnhanceProps) => {
    log.debug("TreeEnhance");

    const { message } = App.useApp();
    const kyeRef = useRef<string[]>([]) ;
    const [treeData, setTreeData] = React.useState<DataNode[]>([]) ;
    const [checkedKeys,setCheckedKeys] = React.useState<string[]>([]) ;
    const [expandedKeys,setExpandedKeys] = React.useState<React.Key[]>([]) ;
    const [loading,setLoading] = React.useState<boolean>(true) ;

    useEffect(() => {
        requestGet<AuthorityHandleTreeData>(dataUrl)
            .then(res => {
                kyeRef.current = res.data.authorityKeys ;
                setTreeData(parseIcon(res.data.treeData)) ;
                setCheckedKeys(res.data.authorityKeys) ;
                setExpandedKeys(res.data.expandKeys) ;
                setLoading(false) ;
            });
    },[id]) ;

    const onCheck = (checkedKeysValue: any) => {
        setCheckedKeys(checkedKeysValue) ;
    };
    const onExpand = (expandedKeysValue: React.Key[]) => {
        setExpandedKeys(expandedKeysValue);

    };
    const undoChanges = () => {
        setCheckedKeys(kyeRef.current) ;
    } ;
    const refreshPermissions = async () => {
        if (refreshUrl === undefined){
            return ;
        }
        await requestGet(refreshUrl).then(res => res) ;
        message.success("刷新权限成功") ;
    } ;
    const updateAuthority = async () => {
        let compRes = compareArray(kyeRef.current, checkedKeys);
        if (compRes.isUpdate){
            setLoading(true) ;
            compRes.id = id ;
            delete compRes.isUpdate ;
            let res = await requestPost<number>(updateUrl,compRes).then(res => res) ;
            log.debug("更新权限结果", res) ;
            if (res.data >0){
                message.success("更新成功") ;
                setLoading(false) ;
                kyeRef.current = checkedKeys ;
            }else {
                message.error("更新失败") ;
                setLoading(false) ;
            }
        }else {
            message.info("没有菜单更新") ;
            log.debug("权限无更新，不需要更新") ;
        }
    };
    return (
        <>
            <Spin spinning={loading}>
                <Tree
                    showIcon={true}
                    style={{paddingInlineStart: "50px"}}
                    treeData={treeData}
                    expandedKeys={expandedKeys}
                    checkedKeys={checkedKeys}
                    checkable
                    onCheck={onCheck}
                    onExpand={onExpand}
                />
            </Spin>
            <Divider/>
            <Flex
                style={{marginTop: "20px"}}
                justify={"space-evenly"}
            >
                <Button type={"primary"} onClick={updateAuthority} loading={loading}>更改权限</Button>
                <Button onClick={refreshPermissions}>刷新权限</Button>
                <Button onClick={undoChanges}>撤销更改</Button>
            </Flex>
        </>
    );
};

export default TreeEnhance;